package cn.lzg.common.core.session;

import java.util.concurrent.ConcurrentHashMap;

import com.google.protobuf.GeneratedMessage;

import cn.lzg.common.core.model.Response;
import cn.lzg.common.core.serial.Serializer;

public class SessionManager {
	private static final ConcurrentHashMap<String, Session> onlineSessions = new ConcurrentHashMap<>();

	/**
	 * 加入
	 * 
	 * @param userId
	 * @param session
	 */
	public static boolean putSession(String userId, Session session) {
		if (!onlineSessions.containsKey(userId)) {
			boolean success = onlineSessions.put(userId, session) == null ? true : false;
			return success;
		}
		return false;
	}

	/**
	 * 获取Session
	 * 
	 * @param userId
	 * @return
	 */
	public static Session getSession(String userId) {
		return onlineSessions.get(userId);
	}

	/**
	 * 移除Session
	 * 
	 * @param userId
	 * @return
	 */
	public static Session removeSession(String userId) {
		return onlineSessions.remove(userId);
	}

	/**
	 * 发送消息
	 * 
	 * @param targetUserId
	 *            向该用户发送消息
	 * @param module
	 * @param cmd
	 * @param message
	 */
	public static <T extends Serializer> void sendMessage(String targetUserId, short module, short cmd, T message) {
		Session session = onlineSessions.get(targetUserId);
		if (session != null && session.isConnected()) {
			Response response = new Response(module, cmd, message.getBytes());
			session.write(response);
		}
	}
	
	/**
	 * 发送消息[protoBuf协议]
	 * @param <T>
	 * @param playerId
	 * @param message
	 */
	public static <T extends GeneratedMessage> void sendMessage(String playerId, short module, short cmd, T message){
		Session session = onlineSessions.get(playerId);
		if (session != null && session.isConnected()) {
			Response response = new Response(module, cmd, message.toByteArray());
			session.write(response);
		}
	}
	
	/**
	 * 用户是否在线
	 * @param userId
	 * @return
	 */
	public static boolean isUserOnline(String userId) {
		return onlineSessions.containsKey(userId);
	}
	
}
